package net.awpspace.mobile.management.note;

import java.util.Vector;

import javax.microedition.rms.RecordStore;

public class Dao {

	private static RecordStore rs = null;
	public static final String DB_NAME = "database";

	// There is no user interface, go ahead and shutdown

	private static void openRecStore() {
		try {
			// Create record store if it does not exist
			rs = RecordStore.openRecordStore(DB_NAME, true);
		} catch (Exception e) {
			db(e.toString());
		}
	}

	private static void closeRecStore() {
		try {
			rs.closeRecordStore();
		} catch (Exception e) {
			db(e.toString());
		}

	}

	public static void addToDB(Note note) {
		openRecStore();
		byte[] data = Convert.parserString(note).getBytes();
		try {
			rs.addRecord(data, 0, data.length);
		} catch (Exception e) {
			db(e.toString());
			e.printStackTrace();
		}
		closeRecStore();
	}

	public static void editNote(Note note, int index) {
		openRecStore();
		System.out.println("dao: " + Convert.parserString(note));
		System.out.println("INDEX" + index);
		byte[] data = Convert.parserString(note).getBytes();
		try {
			rs.setRecord(index + 1, data, 0, data.length);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("Ex này :D");
			e.printStackTrace();
		}

		closeRecStore();
	}
	
	public static void delete(int index){
		openRecStore();
		byte[] data = "deleted".getBytes();
		try {
			rs.setRecord(index + 1, data, 0, data.length);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("Ex này :D");
			e.printStackTrace();
		}
		closeRecStore();
		System.out.println("delete ok");
	}

	public static Vector readDB() {
		openRecStore();
		Vector list = new Vector();
		try {
			byte[] recData = new byte[1024];
			int len;
			for (int i = 1; i <= rs.getNumRecords(); i++) {
				len = rs.getRecord(i, recData, 0);
				String obj = new String(recData, 0, len);
				if (obj.equals("deleted")) {
					//bỏ qua
				} else
					list.addElement(Convert.parserNote(obj));
			}
		} catch (Exception e) {
			db("EX ở đây");
		}
		closeRecStore();
		return list;
	}

	public static void test(Vector list) {
		System.out.println("--------------");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(Convert.parserString((Note) list.elementAt(i)));
		}
	}

	private static void db(String str) {
		System.err.println("Msg: " + str);
	}

}
